<template>
    <div class="menu" ref="flowMenuRef">
        <el-scrollbar>
            <el-collapse v-model="activeComponentType" accordion @change="collapseChange">
                <el-collapse-item
                    v-for="comType in componentTypeList"
                    :key="comType.type"
                    :title="comType.desc"
                    :name="comType.type"
                >
                    <div
                        class="flow-item"
                        v-for="flow in flowChartList"
                        :key="flow.id"
                        :class="{ ['item-' + 'flow-rect']: !flow.componentIcon }"
                        draggable="true"
                        :data-componentId="flow.id"
                    >
                        <template v-if="flow.componentIcon">
                            <img :src="flow.componentIcon" :draggable="false" />
                        </template>
                        <span>{{ flow.componentName }}</span>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-scrollbar>
    </div>
</template>

<script>
import Req from '@/services/req.js';
import EnumUtils from '@/utils/enumUtils.js';
export default {
    name: 'FlowMenu',
    props: {
        graph: {
            type: Object,
            default: Object.create(null)
        }
    },
    data() {
        return {
            menuList: [], // 原始菜单数据
            componentType: '', // 组件类型
            activeComponentType: 'BASIC', // 当前激活组件类型
            componentTypeList: [], // 组件列表数据
            componentList: [], // 组件数据
            flowChartList: [] // 流程列表
        };
    },
    mounted() {
        // 如果没有数据，则默认添加开始和结束
        this.$bus.on('drawDefaultNodeEvent', isNoNode => {
            this.drawDefaultNode(isNoNode);
        });
        // 获取左侧菜单数据
        this.getMenuList();
        // 组件拖拽
        this.addNode();
        // 阻止默认动作
        document.addEventListener(
            'drop',
            e => {
                e.preventDefault();
            },
            false
        );
    },
    methods: {
        // 获取左侧菜单数据
        async getMenuList() {
            const { status, result } = await Req.get('/data/getMenuList.json');
            if (status.statusCode === 0) {
                // 保存原始菜单数据，供过滤时使用
                this.menuList = result.items;
                this.dataProcess(this.menuList);
            } else {
                this.$message.error(status.statusReason);
            }
        },
        // 左侧数据加工，根据componentType分开
        dataProcess(menuList) {
            let obj = {};
            let componentTypeList = [];
            menuList.forEach(item => {
                if (!obj[item.componentType]) {
                    componentTypeList.push({
                        type: item.componentType,
                        desc: item.componentTypeDesc
                    });
                    obj[item.componentType] = true;
                }
            });
            this.componentTypeList = componentTypeList;
            // 初始化过滤组件数据
            this.filterComponentList();
        },
        addNode() {
            setTimeout(() => {
                // 给左侧菜单项添加dragend事件
                let flowItems = [...this.$refs.flowMenuRef.querySelectorAll('.flow-item')];
                flowItems.forEach(item => {
                    item.addEventListener('dragend', e => {
                        const componentid = e.target.dataset.componentid;
                        let component = this.menuList.find(item => {
                            return item.id === componentid;
                        });
                        this.$emit('canvas-add-node', e, component);
                    });
                });
            }, 1000);
        },
        // 添加开始和结束节点
        async drawDefaultNode(isNoNode) {
            if (isNoNode) {
                let nodes = [];
                // 获取当前画布宽度和高度
                const graphWidth = this.graph.get('width');
                const graphHeight = this.graph.get('height');
                const nodeY = graphHeight / 2; // 节点y坐标
                this.flowChartList.forEach((item, index) => {
                    // 节点x坐标
                    let nodeX = graphWidth / 2;
                    if (index === 0) {
                        nodeX -= 150;
                    }
                    // 节点id
                    let nodeId = 'node' + (index + 1);
                    // 生成节点数据
                    let graphicObj = item.graphicVO || {};
                    item.id = nodeId; // 修改node节点id
                    item.graphicVO = null;
                    graphicObj.id = nodeId;
                    graphicObj.x = nodeX;
                    graphicObj.y = nodeY;
                    graphicObj.size = [50, 50];
                    graphicObj.data = item;
                    graphicObj.label = item.componentName;
                    graphicObj.componentType = item.componentType;
                    graphicObj.type = 'circle-node';
                    graphicObj.labelCfg = {
                        fontSize: 12,
                        textAlign: 'center'
                    }
                    // icon
                    if (item.componentIcon) {
                        graphicObj.logoIcon = {
                            show: true,
                            img: item.componentIcon,
                            iconStyle: {
                                width: 30,
                                height: 30,
                                left: 0,
                                top: 0
                            }
                        }
                    }
                    // 全局样式
                    graphicObj.style = {
                        fill: '#fff'
                    }
                    nodes.push(graphicObj);
                })
                const flowChartData = {
                    nodes,
                    edges: []
                };
                if (this.graph?.cfg) {
                    this.graph.changeData(flowChartData);
                }
            }
        },
        // 展开
        collapseChange() {
            // 依据组件类型，过滤组件数据
            this.filterComponentList();
            // 绑定拖拽事件
            this.addNode();
        },
        // 过滤组件数据
        filterComponentList() {
            this.flowChartList = [];
            let flowChartList = [];
            // 基础组件
            if (this.activeComponentType === 'BASIC') {
                flowChartList = this.menuList
                    .filter(item => {
                        return EnumUtils.getFlowType().includes(item.componentCode);
                    })
                    .map(component => {
                        component.shape = 'circle-node'; // 开始和结束设置成圆形
                        return component;
                    });
            } else {
                flowChartList = this.menuList
                    .filter(item => {
                        return item.componentType === this.activeComponentType;
                    })
                    .map(component => {
                        component.shape = 'rect-node';
                        return component;
                    });
            }
            this.flowChartList = flowChartList;
        }
    }
};
</script>

<style src="./Index.scss" lang="scss" scoped></style>
